﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using AutoPartsSearch.Domain.Entities;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace AutoPartsSearch.Domain.Common
{
    public static class Converter
    {
        private static TimeZoneInfo MoldTimeZone = null;

        public static string ToXml(IEnumerable<int> dictIds)
        {
            var xdoc = new XDocument(
                new XDeclaration("1.0", "utf-8", null),
                new XElement("Dictionaries",
                    from id in dictIds
                    select new XElement("Dictionary",
                        new XAttribute("Id", id)
                    )
                )
            );
            return xdoc.ToString();
        }

        public static string ToXml(IEnumerable<Dictionary> dicts)
        {
            return ToXml(dicts.Select(x => x.Id));
        }

        public static IEnumerable<Dictionary> FromXml(string xml)
        {
            var result = XDocument.Parse(xml).Element("Dictionaries").Elements("Dictionary")
                .Select(xelem => new Dictionary(int.Parse(xelem.Attribute("Id").Value)));
            return result;
        }

        public static string ToJsonArray<T>(IEnumerable<T> source)
        {
            var serializer = new JavaScriptSerializer();
            var result = serializer.Serialize(source);
            return result;
        }

        public static object GetIdOrNull(Dictionary dictionary)
        {
            if (dictionary == null)
                return null;
            return dictionary.Id;
        }

        public static DateTime ConvertToMoldTime(DateTime date)
        {
            return TimeZoneInfo.ConvertTime(date, GetMoldTimeZone());
        }

        public static DateTime ConvertToMoldTimeFromUTC(DateTime date)
        {
            var utcDate = new DateTime(date.Year, date.Month, date.Day, date.Hour, date.Minute, date.Second,
                                       DateTimeKind.Utc);
            return TimeZoneInfo.ConvertTime(date, GetMoldTimeZone());
        }

        private static TimeZoneInfo GetMoldTimeZone()
        {
            if (MoldTimeZone == null)
            {
                var moldZone = "E. Europe Standard Time";
                MoldTimeZone = TimeZoneInfo.FindSystemTimeZoneById(moldZone);
            }
            return MoldTimeZone;
        }
    }
}
